"use strict";
const { Model } = require("sequelize");
const bcrypt = require("bcrypt");
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.User.hasMany(models.Course, { as: "courses" });
      models.User.belongsToMany(models.Course, { through: "Like" });
      models.User.hasMany(models.File, { as: "files" });
    }
  }
  User.init(
    {
      username: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: "用户名不能为null",
          notEmpty: "用户名不能为空",
          len: [5, 100],
        },
      },
      nickname: DataTypes.STRING,
      password: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: "密码不能为null",
          notEmpty: "密码不能为空",
        },
        set(value) {
          if (value.length >= 6 && value.length <= 50) {
            // 密码hash,10轮
            this.setDataValue("password", bcrypt.hashSync(value, 10));
          } else {
            throw new Error("密码长度在6-50之间");
          }
        },
      },
      introduce: DataTypes.TEXT,
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: "邮箱不能为null",
          notEmpty: "邮箱不能为空",
          isEmail: true,
        },
      },
      avatar: DataTypes.STRING,
      role: DataTypes.TINYINT,
      sex: {
        type: DataTypes.TINYINT,
        comment: "0:保密,1:男,2:女",
      },
      phone: DataTypes.STRING,
      company: DataTypes.STRING,
    },
    {
      sequelize,
      modelName: "User",
    }
  );
  return User;
};
